﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Task3_GCD
{
    class Task3_GCD
    {
        static void Main(string[] args)
        {
            int firstNumber;
            GetNumberFromInput(out firstNumber, "first");
            int secondNumber;
            GetNumberFromInput(out secondNumber, "second");

            int greatestCommonDivisor = GCD(firstNumber, secondNumber);
            Console.WriteLine("The greatest common divisor of {0} and {1} is {2}.", firstNumber, secondNumber, greatestCommonDivisor);
        }

        private static void GetNumberFromInput(out int value, string number)
        {
            Console.Write("Please, enter the " + number + " number: ");
            string inputNumberLine = Console.ReadLine();
            bool parseStringResult = int.TryParse(inputNumberLine, out value);
            while (!parseStringResult || value == 0)
            {
                Console.Write("Incorrect input! Please, enter the " + number + " number: ");
                inputNumberLine = Console.ReadLine();
                parseStringResult = int.TryParse(inputNumberLine, out value);
            }
        }

        private static void SwapValues(int firstNumber, int secondNumber)
        {
            if (firstNumber == null)
            {
                throw new NullReferenceException();
            }
            if (secondNumber == null)
            {
                throw new NullReferenceException();
            }
            if (firstNumber == 0)
            {
                throw new ArgumentOutOfRangeException();
            }
            if (secondNumber == 0)
            {
                throw new ArgumentOutOfRangeException();
            }

            int temp = firstNumber;
            firstNumber = secondNumber;
            secondNumber = temp;
        }

        private static int GCD(int firstNumber, int secondNumber)
        {
            if (firstNumber == null)
            {
                throw new NullReferenceException();
            }
            if (secondNumber == null)
            {
                throw new NullReferenceException();
            }
            if (firstNumber == 0)
            {
                throw new ArgumentOutOfRangeException();
            }
            if (secondNumber == 0)
            {
                throw new ArgumentOutOfRangeException();
            }

            if (firstNumber < secondNumber)
            {
                SwapValues(firstNumber, secondNumber);
            }
            int remainder = firstNumber % secondNumber;
            while (remainder != 0)
            {
                firstNumber = secondNumber;
                secondNumber = remainder;
                remainder = firstNumber % secondNumber;
            }
            return secondNumber;
        }        
    }
}
